package com.wofish.oauth.controller;

import com.wofish.common.core.domain.JsonRsp;
import com.wofish.common.utils.IpUtils;
import com.wofish.core.annotation.ParamValid;
import com.wofish.core.dto.BusiStatus;
import com.wofish.oauth.account.domain.MemberAccount;
import com.wofish.oauth.account.service.IMemberAccountService;
import com.wofish.oauth.dto.LoginParam;
import com.wofish.oauth.shiro.ShiroKit;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Date;

/**
 * 登录接口类
 */
@Slf4j
@RestController
@RequestMapping("/api/v1/oauth")
public class RegisterController extends BaseController{

    /** 密码强度检查正则，必须包括字母和数字，长度为6到16 */
    private static final String PASSWORD_REGIX = "^(?=.*\\d)(?=.*[A-z]).{6,16}$";

    @Autowired
    private IMemberAccountService memberAccountService;


    //header 公参
    @ParamValid
    @PostMapping("/register")
    public JsonRsp<String> register(@RequestBody @Valid LoginParam loginParam,
                                    BindingResult result,HttpServletRequest request) {
        log.info("register loginParam:{}",loginParam);


        MemberAccount accountByUsername = memberAccountService.findAccountByUsername(loginParam.getUsername());
        if(accountByUsername != null){
            return new JsonRsp<>( BUSI_NORMAL, BusiStatus.USER_EXIST.getDesc());
        }

        String ipAddress = IpUtils.getIpAddr(request);
        //随机数盐
        String salt = RandomStringUtils.randomAlphanumeric(20);
        String wofishNo = RandomStringUtils.randomNumeric(7);
        Date date = new Date();
        //原密码加密（通过username + salt作为盐）
        String encodedPassword = ShiroKit.md5(loginParam.getPassword(), loginParam.getUsername() + salt);
        MemberAccount memberAccount = new MemberAccount();
        memberAccount.setLoginType(loginParam.getLoginType());
        memberAccount.setLoginAccount(loginParam.getUsername());
        memberAccount.setPassword(encodedPassword);
        memberAccount.setSalt(salt);
        memberAccount.setWofishNo(Long.valueOf(wofishNo));
        memberAccount.setSignTime(date);
        memberAccount.setUpdateTime(date);
        memberAccount.setRegisterIp(ipAddress);
        memberAccount.setApp(APP_ID);

        int row = memberAccountService.insertMemberAccount(memberAccount);
        log.info("register memberAccount row:{}",row);

        return new JsonRsp<>(row > 0 ? BUSI_NORMAL : BUSI_ERROR, SUCCESS);

    }


}
